/*- coding = utf-8 -*-
@Time : 2023/7/10 14:25
@Author : 管茂良
@File : useFunc.ts
@web  : www.php-china.com
@Software: WebStorm
*/

import {onMounted, ref, render, useAttrs, useSlots, h, watch, nextTick} from "vue";
import {useIntersectionObserver} from "@vueuse/core";
import ImgDialog from "../cpns/imgDialog/index"

export const useFunc = (props: any) =>{
    let attrs = useAttrs()
    let error = !!useSlots().error;
    let imgRef =ref()
    let isCheckImg =ref(false);//是否查看图片

    let imgStatus = ref({
        isLoading:true,//是否记载
        loadingStatus:true,//加载状态 成功true或者失败false
    })

    const handleCheckImgExists = (imgObj,imgUrl:string) => {
        imgObj.src = imgUrl
        imgObj.onload = function(res) {
            imgStatus.value.loadingStatus = true;
            imgStatus.value.isLoading = false;
        }
        imgObj.onerror = function(err) {
            imgStatus.value.loadingStatus = false;
            imgStatus.value.isLoading = false;
        }
    }

    const handleListenerImgInView = ()=>{
        //监听元素是否在可视窗口
        const {stop} = useIntersectionObserver(imgRef.value,async ([{ isIntersecting }], observerElement)=>{
            //当监听的元素成功进入视口区域，isIntersecting为true
            if(isIntersecting){
                // 主动停止检测元素可见性
                stop()
                await handleCheckImgExists(imgRef.value,props.src)
            }
        },{ threshold: 0 })
    }

    //查看图片
    const handleCheckImg = ()=>{
        if(!props.isShowImgDialog)return
        let divTag = document.createElement("div")
        divTag.setAttribute("style","transition:opacity 0.1s;opacity:0;")
        let body = document.body;
        body.appendChild(divTag)

        const imgDialogProps = { imgList: props.imgList };

        render(h(ImgDialog,imgDialogProps),divTag)
        setTimeout(()=>{
            document.documentElement.style.overflowY = 'hidden';
            divTag.setAttribute("style","transition:opacity 0.1s;opacity:1")
        },200)
    }
    watch(()=>props.src,()=>{
        nextTick(async () => {
            await handleCheckImgExists(imgRef.value, props.src)
        })
        imgStatus.value.loadingStatus = true;
    },{deep:true})
    onMounted(()=>{
        handleListenerImgInView()
    })
    return {
        attrs,error,imgStatus,imgRef,handleCheckImg
    }
}
